package digester;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.digester3.binder.RulesBinder;
import org.apache.commons.digester3.binder.RulesModule;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.Map;

public class TestDigesterParser {

    public static void main(String[] args) {


        //加载配置文件，获得解析器
        Digester digester= DigesterLoader
                .newLoader(new FromXmlRulesModule() {
                    @Override
                    protected void loadRules() {
                        loadXMLRules(getClass().getClassLoader().getResource("digester/rule.xml"));
                    }
                })
                .newDigester();


        //准备一个空的根元素所对应的对象，交给解析器，解析器会将解析的数据set到这个对象中
        ClassBean classBean=new ClassBean();
        digester.push(classBean);

        //解析xml文件
        try {
            digester.parse(TestDigesterParser.class
                                             .getClassLoader()
                                             .getResourceAsStream("students.xml"));

        } catch (Exception e) {
            e.printStackTrace();
        }


//        System.out.println(classBean.getNo());
//        StudentBean studentBean=classBean.findStudent(2);
//        System.out.println(studentBean.getName());
//        System.out.println(studentBean.getSex());


        Map<Integer,StudentBean> students=classBean.getStudents();

        students.forEach((id,student)->{
            System.out.println(student.getId()+" "+student.getName()+" "+student.getSex());
        });



    }
}
